<template>
  <div class="elderly-container">
    <el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
      <el-col :span="24" class="text-center">
        <div class="title-wrapper">
          <i class="el-icon-user el-icon--large"></i>
          <h1 class="main-title">独居老人信息管理系统</h1>
          <p class="sub-title">“关爱独居老人，构建和谐社区”</p>
        </div>
      </el-col>
    </el-row>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="老人详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="老人信息" direction="vertical" :column="4" border>
        <el-descriptions-item label="老人ID" :span="2">{{ currentElderly.elderlyId }}</el-descriptions-item>
        <el-descriptions-item label="姓名" :span="2">{{ currentElderly.elderlyName }}</el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">{{ currentElderly.elderlyStatus || '无' }}</el-descriptions-item>
        <el-descriptions-item label="日用水量(升)" :span="2">{{ currentElderly.dailyWaterConsumption ? currentElderly.dailyWaterConsumption + ' 升' : '无' }}</el-descriptions-item>
        <el-descriptions-item label="用水记录日期" :span="2">{{ formatDate(currentElderly.waterRecordDate) }}</el-descriptions-item>
        <el-descriptions-item label="联系电话" :span="2">{{ currentElderly.elderlyMobile || '无' }}</el-descriptions-item>
        <el-descriptions-item label="详细地址" :span="4">{{ currentElderly.detailedAddress || '无' }}</el-descriptions-item>
        <el-descriptions-item label="紧急联系人" :span="2">{{ currentElderly.emergencyContact || '无' }}</el-descriptions-item>
        <el-descriptions-item label="紧急联系电话" :span="2">{{ currentElderly.emergencyMobile || '无' }}</el-descriptions-item>
        <el-descriptions-item label="与紧急联系人关系" :span="4">{{ currentElderly.emergencyRelation || '无' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="4">{{ currentElderly.remarks || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑老人信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-form-item label="老人ID" prop="elderlyId" disabled>
          <el-input v-model="editForm.elderlyId"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="elderlyName">
          <el-input v-model="editForm.elderlyName"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="editForm.detailedAddress"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="elderlyMobile">
          <el-input v-model="editForm.elderlyMobile"></el-input>
        </el-form-item>
        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input v-model="editForm.emergencyContact"></el-input>
        </el-form-item>
        <el-form-item label="紧急联系电话" prop="emergencyMobile">
          <el-input v-model="editForm.emergencyMobile"></el-input>
        </el-form-item>
        <el-form-item label="与紧急联系人关系">
          <el-input v-model="editForm.emergencyRelation"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="elderlyStatus">
          <el-select v-model="editForm.elderlyStatus" placeholder="请选择状态">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="关注" value="关注"></el-option>
            <el-option label="异常" value="异常"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用水记录日期" prop="waterRecordDate">
          <el-date-picker
            v-model="editForm.waterRecordDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="日用水量(升)" prop="dailyWaterConsumption">
          <el-input v-model.number="editForm.dailyWaterConsumption" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remarks" type="textarea" rows="3"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 新增对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增老人信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="姓名" prop="elderlyName">
          <el-input v-model="addForm.elderlyName"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="addForm.detailedAddress"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="elderlyMobile">
          <el-input v-model="addForm.elderlyMobile"></el-input>
        </el-form-item>
        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input v-model="addForm.emergencyContact"></el-input>
        </el-form-item>
        <el-form-item label="紧急联系电话" prop="emergencyMobile">
          <el-input v-model="addForm.emergencyMobile"></el-input>
        </el-form-item>
        <el-form-item label="与紧急联系人关系">
          <el-input v-model="addForm.emergencyRelation"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="elderlyStatus">
          <el-select v-model="addForm.elderlyStatus" placeholder="请选择状态">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="关注" value="关注"></el-option>
            <el-option label="异常" value="异常"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用水记录日期" prop="waterRecordDate">
          <el-date-picker
            v-model="addForm.waterRecordDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="日用水量(升)" prop="dailyWaterConsumption">
          <el-input v-model.number="addForm.dailyWaterConsumption" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addForm.remarks" type="textarea" rows="3"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 数据操作区：移除日期查询组件，调整布局 -->
    <el-row>
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px; align-items: center;">
        <el-col :span="8">
          <el-input 
            placeholder="输入姓名进行查询" 
            v-model="searchName" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-select 
            v-model="searchStatus" 
            placeholder="按状态筛选" 
            style="width: 100%;"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="正常" value="正常"></el-option>
            <el-option label="关注" value="关注"></el-option>
            <el-option label="异常" value="异常"></el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button 
            type="primary" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-search"></i> 搜索
          </el-button>
        </el-col>
        <el-col :span="3">
          <el-button 
            type="success" 
            @click="resetSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-col>
        <el-col :span="3">
          <el-button 
            type="primary" 
            @click="openAddDialog" 
            style="width: 100%;"
          >
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </el-col>
      </el-row>
      
      <!-- 表格部分：新增【详细地址】列，放在姓名与状态之间 -->
      <el-table 
        :data="filteredData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
        @sort-change="handleSortChange"
      >
        <el-table-column 
          prop="elderlyId" 
          label="老人ID" 
          width="100" 
          align="center" 
          sortable="custom"
        ></el-table-column>
        <el-table-column prop="elderlyName" label="姓名" align="center" width="150"></el-table-column>
        <!-- 新增详细地址列：支持超长文本tooltip提示 -->
        <el-table-column 
          prop="detailedAddress" 
          label="详细地址" 
          align="center" 
          width="350"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column 
          prop="elderlyStatus" 
          label="状态" 
          width="100" 
          align="center"
        ></el-table-column>
        <el-table-column 
          prop="dailyWaterConsumption" 
          label="日用水量(升)" 
          width="140" 
          align="center"
          sortable="custom"
        ></el-table-column>
        <el-table-column 
          prop="waterRecordDate" 
          label="用水记录日期" 
          width="150" 
          align="center" 
          sortable="custom"
        >
          <template #default="scope">{{ formatDate(scope.row.waterRecordDate) }}</template>
        </el-table-column>
        <el-table-column 
          prop="elderlyMobile" 
          label="联系电话" 
          width="140" 
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" @click="openDetailDialog(scope.row)">
                <i class="el-icon-view"></i> 查看
              </el-button>
              <el-button type="warning" size="mini" @click="openEditDialog(scope.row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button type="danger" size="mini" @click="deleteElderly(scope.row.elderlyId)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'


// 对话框状态
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)

// 搜索条件：移除日期查询相关变量
const searchName = ref('')
const searchStatus = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 排序相关
const sortProp = ref('')
const sortOrder = ref('')

// 数据存储
const elderlyList = ref([])
const filteredData = ref([])

// 表单引用
const editFormRef = ref(null)
const addFormRef = ref(null)

// 当前选中的老人信息
const currentElderly = reactive({
  elderlyId: '',
  elderlyName: '',
  detailedAddress: '',
  elderlyMobile: '',
  emergencyContact: '',
  emergencyMobile: '',
  emergencyRelation: '',
  elderlyStatus: '',
  waterRecordDate: '',
  dailyWaterConsumption: null,
  remarks: ''
})

// 编辑表单数据
const editForm = reactive({
  elderlyId: '',
  elderlyName: '',
  detailedAddress: '',
  elderlyMobile: '',
  emergencyContact: '',
  emergencyMobile: '',
  emergencyRelation: '',
  elderlyStatus: '',
  waterRecordDate: '',
  dailyWaterConsumption: null,
  remarks: ''
})

// 新增表单数据
const addForm = reactive({
  elderlyName: '',
  detailedAddress: '',
  elderlyMobile: '',
  emergencyContact: '',
  emergencyMobile: '',
  emergencyRelation: '',
  elderlyStatus: '',
  waterRecordDate: '',
  dailyWaterConsumption: null,
  remarks: ''
})

// 表单验证规则
const rules = reactive({
  elderlyName: [
    { required: true, message: '请输入老人姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '姓名长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  detailedAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 1, max: 200, message: '地址长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  elderlyMobile: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  emergencyContact: [
    { required: true, message: '请输入紧急联系人', trigger: 'blur' },
    { min: 1, max: 50, message: '联系人姓名长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  emergencyMobile: [
    { required: true, message: '请输入紧急联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  elderlyStatus: [
    { required: true, message: '请选择老人状态', trigger: 'change' }
  ],
  waterRecordDate: [
    { required: true, message: '请选择用水记录日期', trigger: 'change' }
  ],
  dailyWaterConsumption: [
    { required: true, message: '请输入日用水量', trigger: 'blur' },
    { type: 'number', message: '必须是数字', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('用水量不能为负数'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ]
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return '无'
  // 处理LocalDate格式的日期
  if (typeof date === 'string') {
    return date
  }
  // 处理Date对象
  return date.toLocaleDateString()
}

// 处理排序变化
function handleSortChange({ prop, order }) {
  sortProp.value = prop;
  sortOrder.value = order;
  if (prop && order) {
    filteredData.value = [...filteredData.value].sort((a, b) => {
      let valA = a[prop];
      let valB = b[prop];
      // 处理日期类型排序
      if (prop === 'waterRecordDate') {
        valA = new Date(valA);
        valB = new Date(valB);
      }
      // 升序/降序处理
      if (order === 'ascending') {
        return valA > valB ? 1 : -1;
      } else {
        return valA < valB ? 1 : -1;
      }
    });
  }
}

// 打开详情对话框
function openDetailDialog(row) {
  dialogVisible.value = true
  const loading = ElLoading.service({ text: '加载详情中...' })
  
  post('/sc/elderly/getById', { id: row.elderlyId }, (res) => {
    loading.close()
    if (res.status === 1 && res.data) {
      Object.assign(currentElderly, res.data);
    } else {
      ElMessage.error(res.msg || '获取详情失败')
    }
  })
}

// 打开编辑对话框
function openEditDialog(elderly) {
  editDialogVisible.value = true
  Object.assign(editForm, {
    elderlyId: elderly.elderlyId,
    elderlyName: elderly.elderlyName,
    detailedAddress: elderly.detailedAddress,
    elderlyMobile: elderly.elderlyMobile,
    emergencyContact: elderly.emergencyContact,
    emergencyMobile: elderly.emergencyMobile,
    emergencyRelation: elderly.emergencyRelation,
    elderlyStatus: elderly.elderlyStatus,
    waterRecordDate: elderly.waterRecordDate,
    dailyWaterConsumption: elderly.dailyWaterConsumption,
    remarks: elderly.remarks
  })
}

// 打开新增对话框
function openAddDialog() {
  addDialogVisible.value = true
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  // 重置表单
  Object.assign(addForm, {
    elderlyName: '',
    detailedAddress: '',
    elderlyMobile: '',
    emergencyContact: '',
    emergencyMobile: '',
    emergencyRelation: '',
    elderlyStatus: '',
    waterRecordDate: '',
    dailyWaterConsumption: null,
    remarks: ''
  })
}

// 提交编辑表单
function submitEditForm() {
  editFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '更新中...' })
    post('/sc/elderly/update', editForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('更新成功！')
        editDialogVisible.value = false
        fetchElderlyList()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    })
  })
}

// 提交新增表单
function submitAddForm() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' })
    post('/sc/elderly/add', addForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('添加成功！')
        addDialogVisible.value = false
        fetchElderlyList()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

// 删除老人信息
function deleteElderly(id) {
  ElMessageBox.confirm(`确定删除ID为 ${id} 的老人信息吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/elderly/delete', { id }, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('删除成功！')
        fetchElderlyList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}

// 搜索处理：移除日期查询逻辑
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  
  // 根据不同的搜索条件调用不同的接口
  if (searchName.value) {
    post('/sc/elderly/getByName', { name: searchName.value }, (res) => {
      loading.close()
      handleSearchResult(res)
    })
  } else if (searchStatus.value) {
    post('/sc/elderly/getByStatus', { status: searchStatus.value }, (res) => {
      loading.close()
      handleSearchResult(res)
    })
  } else {
    // 如果没有搜索条件，获取全部
    fetchElderlyList()
    loading.close()
  }
}

// 处理搜索结果
function handleSearchResult(res) {
  if (res.status === 1 && res.data) {
    filteredData.value = res.data
    showSearchResultMessage()
    currentPage.value = 1
    // 应用当前排序
    if (sortProp.value && sortOrder.value) {
      handleSortChange({ prop: sortProp.value, order: sortOrder.value });
    }
  } else {
    ElMessage.error(res.msg || '搜索失败')
    filteredData.value = []
  }
}

// 显示搜索结果消息
function showSearchResultMessage() {
  if (filteredData.value.length > 0) {
    ElMessage.success(`找到 ${filteredData.value.length} 条记录`)
  } else {
    ElMessage.warning('未找到匹配记录')
  }
}

// 重置搜索：移除日期相关重置
function resetSearch() {
  searchName.value = ''
  searchStatus.value = ''
  filteredData.value = [...elderlyList.value]
  currentPage.value = 1
  // 重置排序
  sortProp.value = ''
  sortOrder.value = ''
}

// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}

// 获取所有老人信息
function fetchElderlyList() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/elderly/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1 && res.data) {
      elderlyList.value = res.data
      filteredData.value = [...res.data]
      // 应用排序
      if (sortProp.value && sortOrder.value) {
        handleSortChange({ prop: sortProp.value, order: sortOrder.value });
      }
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      elderlyList.value = []
      filteredData.value = []
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchElderlyList()
})
</script>

<style scoped>
.elderly-container {
  width: auto;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}

.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}

.el-form-item .el-button,
.el-col .el-button {
  margin-right: 5px;
}

.el-form {
  padding: 10px;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style>